package com.example.bbsbe.service;

import com.example.bbsbe.Repository.ProfileRepository;
import com.example.bbsbe.Repository.UserRepository;
import com.example.bbsbe.entity.profile;
import com.example.bbsbe.entity.user;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;

@Service
@Transactional
public class ProfileService {
    private final ProfileRepository profileRepository;
    private final UserRepository userRepository;
    @PersistenceContext
    private EntityManager entityManager;


    public ProfileService(ProfileRepository profileRepository, UserRepository userRepository, EntityManager entityManager) {
        this.profileRepository = profileRepository;
        this.userRepository = userRepository;
        this.entityManager=entityManager;
    }

    public List<profile> findAll() {
        List<profile> profiles=profileRepository.findByCondition("1");
        for(profile entity : profiles){
            entityManager.detach(entity);
            Long id=entity.getId();
            String icon=entity.getIcon();
            String icon1=entity.getIcon1();
            String icon2=entity.getIcon2();
            String owner=entity.getOwner();
            entity.setUrl("https://www.yushi.chat/api/profiles/"+id+'/');
            entity.setIcon("https://www.yushi.chat/media/"+icon);
            entity.setIcon1("https://www.yushi.chat/media/"+icon1);
            entity.setIcon2("https://www.yushi.chat/media/"+icon2);
            entity.setOwner("https://www.yushi.chat/api/users/"+owner+'/');
        }
        return profiles;
    }
    public Map<String, Object> createProfile(String title, List<String> imgUrls, String text,
                                             String maintext, String username, String type) {
        user owner = userRepository.findIdByName(username);
        Long owner1=owner.getId();
        profile profile = new profile();
        profile.setTitle(title);
        profile.setText(text);
        profile.setMaintext(maintext);
        profile.setType(type);
        profile.setOwner(String.valueOf(owner1));
        profile.setCondition("0");
        profile.setReason("等待审核");
        profile.setViews(0);
        profile.setDiscuss(0);
        profile.setIconnum(imgUrls.size());
        profile.setTime(LocalDate.now().format(DateTimeFormatter.ISO_DATE));
        profile.setUrl(null);
        profile.setIcon("0");
        profile.setIcon1("0");
        profile.setIcon2("0");
        // 处理图片URL
        Pattern pattern = Pattern.compile("https://www.yushi.chat/media/");
        if (imgUrls.size() >= 1) {
            profile.setIcon(pattern.matcher(imgUrls.get(0)).replaceAll(""));
        }
        if (imgUrls.size() >= 2) {
            profile.setIcon1(pattern.matcher(imgUrls.get(1)).replaceAll(""));
        }
        if (imgUrls.size() >= 3) {
            profile.setIcon2(pattern.matcher(imgUrls.get(2)).replaceAll(""));
        }

        profileRepository.save(profile);

        Map<String, Object> response = new HashMap<>();
        response.put("condition", 1);
        return response;
    }

    public Map<String, Object> getProfileDetails(Long profileId,Long cond) {
        Optional<profile> profile = profileRepository.findById(profileId);
        if (cond==null){
            profileRepository.incrementViews(profileId);
        }
        // 增加浏览数
        String owner = profile.get().getOwner();
        Optional<user> user = userRepository.findById(Long.valueOf(owner));
        Map<String, Object> response = new HashMap<>();
        response.put("condition", 1);
        response.put("icon", user.get().getAvatar());
        response.put("icon1",profile.get().getIcon());
        response.put("nickname", user.get().getNickname());
        response.put("discuss", profile.get().getDiscuss());
        response.put("time", profile.get().getTime());
        response.put("title", profile.get().getTitle());
        response.put("level", user.get().getLevel());
        response.put("signature", user.get().getSignature());
        response.put("type", profile.get().getType());
        response.put("maintext", profile.get().getMaintext());
        response.put("views", profile.get().getViews());
        return response;
    }
    public List<Map<String, Object>> getPendingReviews() {
        List<profile> profiles = profileRepository.findByCondition("0");
        List<Map<String, Object>> result = new ArrayList<>();

        for (profile profile : profiles) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", profile.getId());
            item.put("maintext", profile.getMaintext());
            item.put("type", profile.getType());
            item.put("title", profile.getTitle());
            item.put("time", profile.getTime());
            item.put("bool", false);
            result.add(item);
        }
        return result;
    }
    public Map<String, Object> getTotalProfileCount() {
        long count = profileRepository.countByCondition("1");
        Map<String, Object> response = new HashMap<>();
        response.put("condition", 1);
        response.put("procount", count);
        return response;
    }
    public Map<String, Object> getProfileCountByType(String proType) {
        long count = profileRepository.countByTypeAndCondition(proType, "1");
        Map<String, Object> response = new HashMap<>();
        response.put("condition", 1);
        response.put("procount", count);
        return response;
    }
    public List<Map<String, Object>> getProfilesByType(String proType) {
        List<profile> profiles = profileRepository.findByTypeAndCondition(proType, "1");
        List<Map<String, Object>> result = new ArrayList<>();

        for (profile profile : profiles) {
            Map<String, Object> item = new HashMap<>();
            item.put("url", "https://www.yushi.chat/api/profiles/" + profile.getId()+"/");
            item.put("icon", "https://www.yushi.chat/media/" + profile.getIcon());
            item.put("discuss", profile.getDiscuss());
            item.put("owner", "https://www.yushi.chat/api/users/" + profile.getOwner()+"/");
            item.put("text", profile.getText());
            item.put("time", profile.getTime());
            item.put("title", profile.getTitle());
            item.put("type", profile.getType());
            item.put("views", profile.getViews());
            item.put("icon1", "https://www.yushi.chat/media/" + profile.getIcon1());
            item.put("icon2", "https://www.yushi.chat/media/" + profile.getIcon2());
            item.put("iconnum", profile.getIconnum());
            item.put("main", profile.getMaintext());
            result.add(item);
        }
        return result;
    }
    public List<Map<String, Object>> getUserProfiles(String username) {
        String userId = String.valueOf(userRepository.findIdByName(username).getId());

        List<profile> profiles = profileRepository.findByOwner(userId);
        List<Map<String, Object>> result = new ArrayList<>();

        for (profile profile : profiles) {
            Map<String, Object> item = new HashMap<>();
            item.put("id", profile.getId());
            item.put("text", profile.getText());
            item.put("type", profile.getType());
            item.put("condition", profile.getCondition());
            item.put("reason", profile.getReason());
            item.put("title", profile.getTitle());
            item.put("time", profile.getTime());
            result.add(item);
        }
        return result;
    }
    public void deleteProfile(Long profileId) {
        profileRepository.deleteById(profileId);
    }
    public Map<String, Object> approveProfile(Long profileId) {
        Optional<profile> profile = profileRepository.findById(profileId);

        profile.get().setCondition("1");
        profileRepository.save(profile.get());

        // 增加用户经验值
        userRepository.incrementLevel(profile.get().getOwner(), 5);

        Map<String, Object> response = new HashMap<>();
        response.put("condition", 1);
        return response;
    }
    public Map<String, Object> rejectProfile(Long profileId, String reason) {
        Optional<profile> profile = profileRepository.findById(profileId);

        profile.get().setCondition("2");
        profile.get().setReason(reason);
        profileRepository.save(profile.get());

        Map<String, Object> response = new HashMap<>();
        response.put("condition", 1);
        return response;
    }
}
